/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/30 00:08
 */
package org.mechanic.fund.service.wechat.impl;

import org.mechanic.core.Constants;
import org.mechanic.exception.WechatError;
import org.mechanic.exception.WechatErrorException;
import org.mechanic.fund.config.WcBaseInfoProperties;
import org.mechanic.fund.service.wechat.IWcAccessApiService;
import org.mechanic.utils.net.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.text.MessageFormat;
import java.util.Map;

/**
 * 访问微信API相关服务实现
 *
 * @author mechanic
 * @version 0.0.1
 */
@Service
public class WcAccessApiService implements IWcAccessApiService {

    private final
    WcBaseInfoProperties properties;

    @Autowired
    public WcAccessApiService(WcBaseInfoProperties properties) {this.properties = properties;}

    /**
     * 获取企业号token
     * @param corpId 企业号id
     * @param sercet 企业号密钥
     * @return 企业号token字符串
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public String getCropToken(String corpId, String sercet) {
        Assert.notNull(corpId, "企业号的 CorpId 不能为空。");
        Assert.notNull(sercet, "企业号的 Sercet 不能为空。");
        String tokenUrl = MessageFormat.format(
          "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}",
          corpId,
          sercet
        );

        Map value = HttpUtil.get(tokenUrl);

        return this.processWechatApiReturnValue(value).get("access_token").toString();
    }

    /**
     * 获取服务号token
     *
     * @param mpId   服务号id wxea5b317381755917
     * @param sercet 服务号密钥 33abce001e3f6eb17913e74ed2a627ca
     * @return 服务号token字符串
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public String getMpToken(String mpId, String sercet) {
        Assert.notNull(mpId, "服务号的 AppID 不能为空。");
        Assert.notNull(sercet, "服务号的 AppSecret 不能为空。");
        String tokenUrl = MessageFormat.format(
          "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",
          mpId,
          sercet
        );

        Map value = HttpUtil.get(tokenUrl);

        return this.processWechatApiReturnValue(value).get("access_token").toString();
    }

    /**
     * 添加部门到微信企业号
     *
     * @return 微信企业号API返回的消息。详见{@see <a href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E9%83%A8%E9%97%A8">http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E9%83%A8%E9%97%A8</a>}
     */
    @Override
    public Map saveDepartment(String department) {
        Assert.notNull(department, "部门信息不能为空。");
        String departmentApi = MessageFormat.format(
          "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={0}",
          properties.getCorpToken()
        );

        Map value = HttpUtil.post(departmentApi, department);
        return this.processWechatApiReturnValue(value);
    }

    public Map saveUser(String user) {
        Assert.notNull(user, "用户信息不能为空。");
        String userApi = MessageFormat.format(
          "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={0}",
          properties.getCorpToken()
        );
        Map value = HttpUtil.post(userApi, user);
        return this.processWechatApiReturnValue(value);
    }

    private Map processWechatApiReturnValue(Map value) {
        if (value.containsKey("errcode")) {
            Integer errorcode = Integer.parseInt(value.get("errcode").toString());
            if (errorcode != 0) {
                WechatError error = new WechatError();
                error.setErrorCode(Integer.parseInt(value.get("errcode").toString()));
                error.setErrorMsg(value.get("errmsg").toString());
                throw new WechatErrorException(error);
            }
        }
        return value;
    }
}